package com.example.Servlet;

import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@MultipartConfig
@WebServlet(name = "AuatorUploadServlet", value = "/AuatorUploadServlet")
public class AuatorUploadServlet extends HttpServlet {
    private String message;
//    private User user;

    public void init() {
        message = "Hello World!";
    }

    @Override
    protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doOptions(req, resp);
        resp.setHeader("Access-Control-Allow-Origin", "*");
// 允许跨域请求的方法（GET/POST等）
        resp.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
// 允许跨域请求的头信息
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type");
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        response.setContentType("text/html");
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doPost(req, resp);
        Part part=req.getPart("userAuator");
        Gson gson=new Gson();
        Map<String,Object> map=new HashMap<>();
        if (part == null) {
            // 处理文件未找到的情况
            map.put("code", 400);
            map.put("msg", "未找到上传的文件");
            resp.getWriter().append(gson.toJson(map));
            return;
        }
        System.out.println(part.getSubmittedFileName());
        File path=new File(req.getServletContext().getRealPath("upload"));
        if(!path.exists()){
            path.mkdirs();
        }
        String originalName= part.getSubmittedFileName();
        String newName=UUID.randomUUID().toString()+originalName.substring(originalName.lastIndexOf("."));
        File uploadFile=new File(path,newName);
        part.write(uploadFile.getAbsolutePath());
        map.put("code",200);
        map.put("msg","上传成功");
        map.put("filename","upload/"+newName);
        resp.getWriter().append(gson.toJson(map));
        System.out.println(newName);

    }
}
